package ch.ti.bfh.app.loodel.internal.security;

import ch.ti.bfh.app.loodel.domain.member.Member;
import ch.ti.bfh.app.loodel.domain.member.MemberRepository;
import ch.ti.bfh.app.loodel.service.LoodelUserDetails;
import ch.ti.bfh.app.loodel.service.MemberData;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
public class DefaultMemberUserDetailsService implements UserDetailsService {

    private static final List<GrantedAuthority> DEFAULT_AUTHORITIES = AuthorityUtils.createAuthorityList("ROLE_USER");

    private final MemberRepository memberRepository;

    private List<String> adminUsers;

    public DefaultMemberUserDetailsService(MemberRepository memberRepository, List<String> adminUsers) {
        this.memberRepository = memberRepository;
        this.adminUsers = adminUsers;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Member memberByEMail = memberRepository.findByEmail(username);
        if (memberByEMail == null) {
            throw new UsernameNotFoundException(username);
        }
        List<GrantedAuthority> roles = DEFAULT_AUTHORITIES;
        if (adminUsers.contains(memberByEMail.getEmail())) {
            roles = AuthorityUtils.createAuthorityList("ROLE_ADMIN");
        }
        return new LoodelUserDetails(buildMemberData(memberByEMail), roles);
    }

    private MemberData buildMemberData(Member member) {
        return new MemberData(member.getEmail(), member.getFullName());
    }


}
